import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { TodoReply } from './entities/todo-reply.entity';
import { CreateTodoReplyDto } from './dto/create-todo-reply.dto';
import { UpdateTodoReplyDto } from './dto/update-todo-reply.dto';
import { UploadPicturesService } from '../common/upload/upload-pictures.service';

@Injectable()
export class TodoReplyService {
  constructor(
    @InjectRepository(TodoReply)
    private todoReplyRepository: Repository<TodoReply>,
    private uploadPicturesService: UploadPicturesService
  ) {}



  async create(createTodoReplyDto: CreateTodoReplyDto): Promise<TodoReply> {
    const todoReply = this.todoReplyRepository.create(createTodoReplyDto);
    return this.todoReplyRepository.save(todoReply);
  }





  async findById(id: number): Promise<TodoReply> {
    const todoReply = await this.todoReplyRepository.findOne({
      where: { _Identify: id },
    });
    if (!todoReply) {
      throw new NotFoundException(`TodoReply with ID ${id} not found`);
    }
    return todoReply;
  }





  // 新增方法：获取回复详情（包含多张图片）
  async getReplyWithPictures(id: number): Promise<any> {
    const reply = await this.findById(id);
    
    if (reply.picture) {
      // 这里可以调用UploadPicturesService来获取图片信息
      // 暂时返回picture字段，由调用方处理
      return {
        ...reply,
        pictureIds: this.parsePictureIds(reply.picture),
      };
    }
    
    return reply;
  }

  // 解析picture字段中的图片ID
  private parsePictureIds(pictureField: string): string[] {
    if (!pictureField) return [];
    
    // 如果是JSON格式
    try {
      const parsed = JSON.parse(pictureField);
      if (Array.isArray(parsed)) {
        return parsed;
      } else if (typeof parsed === 'string') {
        return [parsed];
      }
    } catch (e) {
      // 不是JSON格式，继续处理
    }
    
    // 如果是逗号分隔的字符串
    if (pictureField.includes(',')) {
      return pictureField.split(',').map(id => id.trim()).filter(id => id);
    }
    
    // 单个图片ID
    return [pictureField];
  }

  // 加载回复的图片（对应Java的loadTodoReplypictures方法）
  private async loadReplyPictures(reply: TodoReply): Promise<void> {
    if (reply.picture) {
      const pictures = await this.uploadPicturesService.findByServiceId(reply.picture);
      reply['uploadpictures'] = pictures;
    }
  }

  // 删除回复
  async remove(id: number): Promise<void> {
    const todoReply = await this.findById(id);
    await this.todoReplyRepository.remove(todoReply);
  }
} 